package com.zzl.car.handle;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzl.car.exception.ZdpException;
import com.zzl.car.context.ZdpResponseBody;
import com.zzl.car.zdpAnnotation.NotResponseBody;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = "com.zzl.car.controller")
//全局处理类
//将响应的数据封装成统一的数据格式
public class ZdpResponseBodyHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //只有supports返回true ，才会执行beforeBodyWrite 对数据进行封装
        //如果返回的类型本身就是zdpResponseBody的话，就没必要进行封装
        //使用@NotResponseBody注解标注的方法也绕过封装
        // || 短路运算
        return !(returnType.getParameterType().equals(ZdpResponseBody.class)
                ||returnType.hasMethodAnnotation(NotResponseBody.class));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //对数据进行封装
        //String 类型不可以直接封装，需要特殊的处理
        System.out.println("ResponseBodyHandler=========");
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在zdpResponseBody里后，再转换为json字符串响应给前端
                return objectMapper.writeValueAsString(new ZdpResponseBody(body));
            } catch (JsonProcessingException e) {
                throw new ZdpException("返回String类型错误");
            }
        }
        // 将原本的数据包装在zdpResponseBody里
        return new ZdpResponseBody<>(body);

    }
}
